package org.dreamwork.jasmine2.parser;

public abstract class JspDirective extends TextNode {
    public static final int TYPE_PAGE = 0;
    public static final int TYPE_TAGLIB = 1;
    public static final int TYPE_INCLUDE = 2;

    protected int type;

    public abstract void parse () throws ParseException;

    protected JspDirective (String content) {
        super ("");
        this.content = content;
    }

    private static boolean isSpace (char ch) {
        return ch >= 0 && ch <= ' ';
    }

    public static JspDirective getDirective (String content) {
        char[] buff = content.toCharArray ();
        StringBuffer key = new StringBuffer ();
        for (int i = skipUntil ("@", buff, 0) + 1; i < content.length (); i++) {
            char ch = content.charAt (i);
            if (isSpace (ch)) {
                if (key.length () > 0) {
                    String s = key.toString ();
                    if ("taglib".equals (s)) {
                        return new TaglibDirective (content);
                    } else if ("page".equals (s)) {
                        return new PageDirective (content);
                    } else if ("include".equals (s)) {
                        return new IncludeDirective (content);
                    }
                } else
                    continue;
            }
            key.append (ch);
        }

        return null;
    }

    public int getType () {
        return type;
    }

    protected static int skipUntil (String s, char[] buff, int cursor) {
        int length = s.length ();
        SKIP:
        for (int i = cursor; i < buff.length; i++) {
            char ch = buff[i];
            if (ch == s.charAt (0)) {
                for (int j = 1; j < length; j++) {
                    if (ch == s.charAt (j)) ch = buff[++i];
                    else continue SKIP;
                }

                return i;
            }
        }
        return -1;
    }
}